package org.nightstudio.common.filter.session;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.nightstudio.common.util.action.ActionUtil;
import org.nightstudio.common.util.constant.FilterConstant;

public class SessionFilter implements Filter {
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (request == null) {
			handleBadRequest(request, response);
			return;
		}
		if (!(request instanceof HttpServletRequest)) {
			handleBadRequest(request, response);
			return;
		}
		if (!(response instanceof HttpServletResponse)) {
			handleBadRequest(request, response);
			return;
		}
		HttpSession session = ((HttpServletRequest) request).getSession(true);
		if (session == null) {
			handleBadRequest(request, response);
			return;
		}
		if (!checkSession(request)) {
			boolean ignore = false;
			String requestUri = ((HttpServletRequest) request).getRequestURI();
			for (String ignorePath : FilterConstant.SESSION_FILTER_IGNORE_PATHES) {
				if (requestUri.endsWith(ignorePath)) {
					ignore = true;
					break;
				}
			}
			if (!ignore) {
				handleBadRequest(request, response);
				return;
			}
		}
		chain.doFilter(request, response);
	}

	private boolean checkSession(ServletRequest request) {
		return true;
	}
	
	private void handleBadRequest(ServletRequest request,
			ServletResponse response) throws ServletException, IOException {
		((HttpServletResponse) response).sendRedirect(ActionUtil.getSessionErrorAction((HttpServletRequest) request));
	}
}
